"use client"
import { getMarkerList, Marker } from "@/api";
import { Feature } from "ol";
import { Point } from "ol/geom";
import VectorLayer from "ol/layer/Vector";
import { fromLonLat } from "ol/proj";
import VectorSource from "ol/source/Vector";
import { useState, useEffect } from "react";
import Map from "ol/Map";
import { circleStyle, iconStyle } from "./util";
import { addLayerGroup } from "@/helper/addLayerGroup";

interface Props {
  map: Map;
}

const MarkerCheckbox: React.FC<Props> = ({ map }) => {

  const [checked, setChecked] = useState(true)
  const [markerList, setMarkerList] = useState<Marker[]>([])


  // 点位数据获取
  useEffect(() => {
    async function main() {
      const data = await getMarkerList()
      setMarkerList(data)
    }
    if (checked) {
      main()
    }
  }, [checked]);

  // 点位控制
  useEffect(() => {

    if (checked) {

      const iconFeatures: Feature<Point>[] = []
      const circleFeatures: Feature<Point>[] = []

      markerList.forEach(item => {
        const iconFeature = new Feature({
          geometry: new Point(fromLonLat([item.lng, item.lat])),
          name: item.name,
          population: 4000,
          rainfall: 500,
        });
        iconFeature.setStyle(iconStyle)
        iconFeatures.push(iconFeature)

        const circleFeature = new Feature({
          geometry: new Point(fromLonLat([item.lng, item.lat])),
          name: item.name,
          population: 4000,
          rainfall: 500,
          style: circleStyle
        });
        circleFeatures.push(circleFeature)
      })


      const iconVectorLayer = new VectorLayer({
        source: new VectorSource({
          features: iconFeatures
        })
      });

      const circleVectorLayer = new VectorLayer({
        source: new VectorSource({
          features: circleFeatures
        })
      });

      const removeCb = addLayerGroup([circleVectorLayer, iconVectorLayer], map)


      return () => {
        removeCb()
      }
    }
  }, [checked, map, markerList]);

  return (
    <input
      className="toggle toggle-sm"
      type="checkbox"
      checked={checked}
      onChange={(e) => setChecked(e.target.checked)}
    />
  )
}

export default MarkerCheckbox